<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Log;

class Login extends Controller
{
    protected $siteId = "aragon";
    protected $md5_key = '64F23B65B3B24392A9F4A884E0AF6657';

    public function index()
    {
        return 'app';
    }

    public function wx_app_login()
    {
        //Android客户端用户授权获取code
        $code = input('code');
        $channel = input('channel');
        if ($code) {
            $WeChat = new WeChat();
            $res = $WeChat->getAccessToken($code);
            if (!isset($res['openid'])) {
                return json($res);
            }

            $json = $WeChat->getUserInfo($res['openid']);
            Log::error('getUserInfo:');
            Log::error($json);

            $userinfo = json_decode($json, true);
            if (!isset($userinfo['openid'])) {
                return json($res);
            }

//            $userinfo = [
//                "openid" => "on9Ei1P5k6umD90FJR7X9HJii9ik",
//                "nickname" => "随风而逝",
//                "sex" => 1,
//                "language" => "zh_CN",
//                "city" => "Hangzhou",
//                "province" => "Zhejiang",
//                "country" => "CN",
//                "headimgurl" => "http://thirdwx.qlogo.cn/mmopen/vi_32/bJK26REcvwhaX3KnnUpnNblzt0ZiaCh26SlUiaSmwlUVyMcyL1C1sqdkR1voYHzCYicp12avibKRCcnFicCSx4MWFtw/132",
//                "privilege" => [],
//                "unionid" => "oZjbMwj_4dwPzJ-tzcRFq6TexxT8",
//            ];

            //导入顺网库中
            $user_sw = $this->sw_user_inducts($userinfo);
            Log::error($user_sw);

            if ($user_sw['result']) {
                $phone = "";
                $memberId = "";
                $token = $this->uuid(); //生成app token
                if (isset($user_sw['phone'])) {
                    $phone = $this->_encrypt($user_sw['phone']);
                    $memberId = $user_sw['memberId'];
                }

                //入库数据
                $data = [];
                $data['token'] = $token;
                $data['phone'] = $phone;
                $data['headimgurl'] = $userinfo['headimgurl'];
                $data['memberName'] = filter_Emoji($userinfo['nickname']);
                $data['memberId'] = $memberId;
                $unionid = $userinfo['unionid'];

                $res = Db::table('vo_app_user')->where('unionid', $unionid)->find();
                if ($res) {
                    //更新操作
                    Db::table('vo_app_user')->where('unionid', $unionid)->update($data);
                } else {
                    //入库操作
                    $data['unionid'] = $unionid;
                    $data['channel'] = $channel;
                    Db::table('vo_app_user')->insert($data);
                }

                //是否登录成功
                if ($phone) {
                    return json(['code' => 200, 'msg' => '登录成功', 'token' => $token]);
                } else {
                    //将手机校验令牌存入redis中
                    //singleAccountToken手机短信校验码
                    $redis = redis_init(5);
                    $redis->setex($user_sw['singleAccountToken'], 1800, $unionid);

                    return json(['code' => 500, 'msg' => '请绑定手机号', 'singleAccountToken' => $user_sw['singleAccountToken']]);
                }
            }

            return json($user_sw);
        }
    }

    public function send_for_mobile()
    {
        $phone = input('phone');
        $singleAccountToken = input('singleAccountToken');
        if (!$phone || !$singleAccountToken) {
            return json(['code' => 500, 'msg' => '参数错误']);
        }

        $redis = redis_init(5);
        $unionid = $redis->get($singleAccountToken);

        $user = Db::table('vo_app_user')->where('unionid', $unionid)->find();
        if (!$user || !$unionid) {
            return json(['code' => 500, 'msg' => '用户不存在']);
        }

        $params = [];
        $params['siteId'] = $this->siteId;
        $params['memberId'] = $user['memberId'];
        $params['mobile'] = $phone;
        $params['singleAccountToken'] = $singleAccountToken;
        $params['time'] = date('YmdHis', time());
        $params['signVersion'] = '1.0';
        $params["sign"] = $this->sw_sign($params);

        $url = "http://interface.kedou.com/front/interface/sendForMobileSingleAccountBind.htm";
//        $url = "http://callback.kedou.com/cs_interface/front/interface/sendForMobileSingleAccountBind.htm";

        $WeChat = new WeChat();
        $res = $WeChat->httpRequest($url, $params);

        return $res;
    }

    public function single_account_bind()
    {
        $code = input('code');
        $phone = input('phone');
        $singleAccountToken = input('singleAccountToken');
        if (!$code || !$phone || !$singleAccountToken) {
            return json(['code' => 500, 'msg' => '参数错误']);
        }

        $redis = redis_init(5);
        $unionid = $redis->get($singleAccountToken);
        $user = Db::table('vo_app_user')->where('unionid', $unionid)->find();
        if (!$user || !$unionid) {
            return json(['code' => 500, 'msg' => '用户不存在']);
        }

        $params = [];
        $params['siteId'] = $this->siteId;
        $params['mobile'] = $phone;
        $params['mobileActiveNo'] = $code;
        $params['time'] = date('YmdHis', time());
        $params['singleAccountToken'] = $singleAccountToken;
        $params['signVersion'] = '1.0';
        $params["sign"] = $this->sw_sign($params);

        $url = "http://interface.kedou.com/front/interface/confirmForSingleAccountBind.htm";
//        $url = "http://callback.kedou.com/cs_interface/front/interface/confirmForSingleAccountBind.htm";

        $WeChat = new WeChat();
        $res = $WeChat->httpRequest($url, $params);
        Log::error('single_account_bind');
        Log::error($res);

        $xml = (array)simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
        $msgId = (string)$xml['Result']['msgId'];
        if ($msgId === "0") {
            $memberId = "";
            if (isset($xml['Result']->items->item->userId)) {
                $memberId = (string)$xml['Result']->items->item->userId;
            }

            Db::table('vo_app_user')->where('unionid', $unionid)->update(['phone' => $this->_encrypt($phone), 'memberId' => $memberId]);

            return json(['code' => 200, 'msg' => '登录成功', 'token' => $user['token'],]);
        } else {
            return json(['code' => 500, 'msg' => '登录失败']);
        }
    }

    private function sw_user_inducts($userinfo)
    {
        //通过unionid 进行 顺网用户导入
        $url = 'http://sso.kedou.com/createByWXUnionID.do';
//        $url = 'http://callback.kedou.com/cs_sso/createByWXUnionID.do';

        $WeChat = new WeChat();

        $extInfo = [
            "nickname" => $userinfo['nickname'],
            "sex" => $userinfo['sex'],
            "headimgurl" => $userinfo['headimgurl']
        ];

        $data = [];
        $data['userId'] = $userinfo['unionid'];
        $data['extInfo'] = json_encode($extInfo);
        $data['siteId'] = $this->siteId;
        $data['timestamp'] = date('YmdHis', time());
        $data['clientIp'] = "127.0.0.1";

        $str = $userinfo['unionid'] . "|" . $data['extInfo'] . "|" . $data['siteId'] . "|" . $data['timestamp'] . "|" . $this->md5_key;
        $sign = strtoupper(md5(strtoupper(urlencode($str))));
        $data['sign'] = $sign;

        $res = $WeChat->httpRequest($url, $data);
        return json_decode($res, true);
    }

    private function uuid()
    {
        //optional for php 4.2.0 and up.随便数播种，4.2.0以后不需要了
        mt_srand((double)microtime() * 10000);
        //根据当前时间（微秒计）生成唯一id
        $charId = strtoupper(md5(uniqid(rand(), true)));
        //$hyphen = chr(45); // "-"
        $hyphen = '';
        $uuid = '' . substr($charId, 0, 8) . $hyphen . substr($charId, 8, 4) . $hyphen . substr($charId, 12, 4) . $hyphen . substr($charId, 16, 4) . $hyphen . substr($charId, 20, 12);
        return $uuid;
    }

    private function sw_sign($params)
    {
        ksort($params);
        $sign = '';
        foreach ($params as $k => $v) {
            $sign = $sign . $v . "|";
        }

        $sign = strtolower(md5($sign . $this->md5_key));
        return $sign;
    }

    //加密函数
    function _encrypt($txt, $key = 'cbox123')
    {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode($ch . $tmp);
    }

    //解密函数
    function _decrypt($txt, $key = 'cbox123')
    {
        $txt = urldecode($txt);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) $j += 64;
            $tmp .= $chars[$j];
        }
        return base64_decode($tmp);
    }
}
